/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React, { Component, Fragment } from 'react';
import PropTypes from 'prop-types';
import isEqual from 'react-fast-compare';
import { isEmpty } from 'lodash';
import FooterToolbar from 'ant-design-pro/lib/FooterToolbar';
import { Icon } from '@blueprintjs/core';

// Dialogs
import { ViewFileInfoDialog } from '../../Dialogs';

// Utils
import { Settings } from '../../../utils';

// Styles
import 'ant-design-pro/lib/FooterToolbar/style/index.css';
import './WorkspaceFooter.css';

// Constants
const { DEFAULT_FILE_NAME } = Settings;

class WorkspaceFooter extends Component {
  state = {
    selectedCube: 'No cube selected',
    fileName: DEFAULT_FILE_NAME,
    isOpenViewFileInfoDialog: false,
    queryInfo: {}
  };

  componentWillMount() {
    const { query, file } = this.props;
    const { queryResultset } = this.props.queryResultset;
    const { cube } = query;

    if (cube) {
      const schemaName = cube.schema !== '' ? cube.schema : cube.catalog;
      const cubeName =
        cube.caption === '' || cube.caption === null ? cube.name : cube.caption;

      this.setState({
        selectedCube: `${schemaName} → ${cubeName}`
      });
    }

    if (file) {
      this.setState({ fileName: this.getFileName(file) });
    }

    if (!isEmpty(queryResultset)) {
      const { width, height, runtime } = queryResultset;

      this.setState({
        queryInfo: {
          width,
          height,
          runtime
        }
      });
    }
  }

  componentWillReceiveProps(nextProps) {
    const queryProps = this.props.query;
    const queryNextProps = nextProps.query;

    const queryResultsetProps = this.props.queryResultset.queryResultset;
    const queryResultsetNextProps = nextProps.queryResultset.queryResultset;

    const fileProps = this.props.file;
    const fileNextProps = nextProps.file;

    if (
      queryProps &&
      (queryNextProps && queryNextProps.cube) &&
      queryProps.cube !== queryNextProps.cube
    ) {
      const { cube } = queryNextProps;
      const schemaName = cube.schema !== '' ? cube.schema : cube.catalog;
      const cubeName =
        cube.caption === '' || cube.caption === null ? cube.name : cube.caption;

      this.setState({
        selectedCube: `${schemaName} → ${cubeName}`
      });
    }

    if (fileProps !== fileNextProps) {
      this.setState({ fileName: this.getFileName(fileNextProps) });
    }

    if (
      queryResultsetProps &&
      queryResultsetNextProps &&
      (queryResultsetProps.width !== queryResultsetNextProps.width ||
        queryResultsetProps.height !== queryResultsetNextProps.height ||
        queryResultsetProps.runtime !== queryResultsetNextProps.runtime)
    ) {
      if (!isEmpty(queryResultsetNextProps)) {
        const { width, height, runtime } = queryResultsetNextProps;

        this.setState({
          queryInfo: {
            width,
            height,
            runtime
          }
        });
      } else {
        this.setState({ queryInfo: {} });
      }
    }
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !isEqual(this.props.query, nextProps.query) ||
      !isEqual(this.props.queryResultset, nextProps.queryResultset) ||
      this.state.selectedCube !== nextState.selectedCube ||
      this.state.fileName !== nextState.fileName ||
      this.state.isOpenViewFileInfoDialog !==
        nextState.isOpenViewFileInfoDialog ||
      !isEqual(this.state.queryInfo, nextState.queryInfo)
    );
  }

  getFileName(file) {
    return file ? file.replace(/^.*[\\/]/, '') : DEFAULT_FILE_NAME;
  }

  handleViewFileInfoDialog = () => {
    this.setState(prevState => ({
      isOpenViewFileInfoDialog: !prevState.isOpenViewFileInfoDialog
    }));
  };

  renderQueryInfo() {
    const { queryInfo } = this.state;
    let chour = new Date().getHours();
    let cminutes = new Date().getMinutes();
    let cdate;
    let runtime;

    if (chour < 10) {
      chour = `0${chour}`;
    }

    if (cminutes < 10) {
      cminutes = `0${cminutes}`;
    }

    cdate = `${chour}:${cminutes}`;
    runtime =
      queryInfo.runtime !== null ? (queryInfo.runtime / 1000).toFixed(2) : '';

    return (
      !isEmpty(queryInfo) && (
        <span>
          <Icon icon="info-sign" iconSize={14} title={false} /> {cdate} /{' '}
          {queryInfo.width} x {queryInfo.height} / {runtime}s
        </span>
      )
    );
  }

  renderContentLeft() {
    const { selectedCube, fileName } = this.state;

    return (
      <ul className="sku-footer-toolbar-items">
        <li>
          <span>
            <Icon icon="cube" iconSize={14} title={false} /> {selectedCube}
          </span>
        </li>
        <li className="m-r-5 m-l-5">
          <Icon icon="slash" title={false} />
        </li>
        <li>
          <button
            type="button"
            className="link-button"
            onClick={this.handleViewFileInfoDialog}
          >
            <Icon icon="document" iconSize={14} title={false} /> {fileName}
          </button>
        </li>
      </ul>
    );
  }

  renderContentRight() {
    return <span>{this.renderQueryInfo()}</span>;
  }

  render() {
    const { file } = this.props;
    const { fileName, isOpenViewFileInfoDialog } = this.state;

    return (
      <Fragment>
        <FooterToolbar
          className="sku-workspace-footer"
          extra={this.renderContentLeft()}
        >
          {this.renderContentRight()}
        </FooterToolbar>

        {isOpenViewFileInfoDialog && (
          <ViewFileInfoDialog
            file={file}
            fileName={fileName}
            type="saiku"
            onClose={this.handleViewFileInfoDialog}
          />
        )}
      </Fragment>
    );
  }
}

WorkspaceFooter.propTypes = {
  query: PropTypes.object.isRequired,
  queryResultset: PropTypes.object.isRequired,
  file: PropTypes.string
};

export default WorkspaceFooter;
